//
//  SelectedSchoolController.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/3/30.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "SelectedSchoolController.h"
#import "LoginAPIManager.h"
#import "AddressPickView.h"

@interface SelectedSchoolController ()<UITextFieldDelegate ,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)UIView *searchView;

@property(nonatomic ,strong)UITextField *searchTextFiled;

@property(nonatomic ,strong)UIImageView *headerBgImageView;

@property(nonatomic ,copy)NSString *city;

@property(nonatomic ,strong)NSArray *data;

@property(nonatomic ,strong)NSMutableArray *sectionIndex;

@property(nonatomic ,strong)AddressPickView *pickerView;

@property(nonatomic ,strong)UILabel *addressLab;

/* 搜索定时器 **/
@property (nonatomic, strong)dispatch_source_t searchTimer;

@end

@implementation SelectedSchoolController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:lWhiteColor] backgroundColor:nil shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:rgba(51, 51, 51, 1),NSFontAttributeName:MFontWithSize(18)} enableScrollEdgeAppearance:YES];

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    self.title = @"选择所在学校";
    self.city = @"广东省 深圳市 宝安区";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.searchView];
    [lApp.window addSubview:self.pickerView];
    [self getAddress];
    self.view.backgroundColor = lWhiteColor;
}

#pragma mark -API
- (void)getAddress
{
    [LoginAPIManager GetAddressListWithParam:@{} result:^(NSDictionary * _Nonnull dic) {
        if ([dic[@"code"] doubleValue] == 1) {
            self.pickerView.data = dic[@"data"];
        }
    }];
}
- (void)loadData
{
    NSMutableDictionary *dic= @{@"city":self.city}.mutableCopy;
    if (self.searchTextFiled.text.length > 0) {
        [dic setObject:self.searchTextFiled.text forKey:@"name"];
    }
    
    [LoginAPIManager GetSchoolListWithParam:dic result:^(NSDictionary * _Nonnull dic) {
        self.data = dic[@"data"];
        self.sectionIndex = @[].mutableCopy;
        for (NSDictionary *dic in self.data) {
            if (dic[@"children"]&&dic[@"name"]) {
                [self.sectionIndex addObject:dic[@"name"]];
            }
        }
        [self.tableView reloadData];
    }];
}
#pragma mark -UITableViewDelegate,UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    
    NSDictionary *rowDic = self.data[indexPath.section];
    NSArray *children = rowDic[@"children"];
    NSDictionary *dic = children[indexPath.row];
    cell.textLabel.text = dic[@"name"];
    cell.detailTextLabel.text = dic[@"city"];
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.data.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth, 32)];
    header.backgroundColor = rgba(245, 245, 245, 1);
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, lScreenWidth - 20, 32)];
    titleLabel.font = MFontWithSize(16);
    titleLabel.text = self.sectionIndex[section];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = rgba(142, 142, 142, 1);
    [header addSubview:titleLabel];
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 32;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSDictionary *dic = self.data[section];
    NSArray *children = dic[@"children"];
    return children.count;
        
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 65;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.block) {
        NSDictionary *dic = self.data[indexPath.section];
        NSArray *children = dic[@"children"];
        self.block(children[indexPath.row]);
        [self.navigationController popViewControllerAnimated:YES];
    }

}

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.sectionIndex;
}

#pragma mark -UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kOrangeLineColor];
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kLineColor];
    
    return  YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
-(void)textEnd:(UITextField *)textField
{
    [self.tableView reloadData];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // 取消定时器
    if (self.searchTimer) {
        dispatch_cancel(self.searchTimer);
        self.searchTimer = nil;
    }
    [self delaySearchText];
    return YES;
}
- (void)modiftyBtnAction
{
    [self endEdit];
    [self.pickerView showView];
}
#pragma -mark 延迟0.5秒搜索
-(void)delaySearchText
{
    // 获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    // 创建一个定时器(dispatch_source_t本质还是个OC对象)
    if (!self.searchTimer) {
        self.searchTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    }
    
    /** 设置定时器的各种属性（几时开始任务，每隔多长时间执行一次）*/
    // (何时开始执行第一个任务, 比当前时间晚0.5秒)
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    // GCD的时间参数，一般是纳秒 NSEC_PER_SEC（1秒 == 10的9次方纳秒）
    uint64_t interval = (uint64_t)(0.5 * NSEC_PER_SEC);
    dispatch_source_set_timer(self.searchTimer, start, interval, 0);
    
    // 设置回调
    dispatch_source_set_event_handler(self.searchTimer, ^{
        //         取消定时器
        dispatch_cancel(self.searchTimer);
        self.searchTimer = nil;
       dispatch_async(dispatch_get_main_queue(), ^{
          [self loadData];
       });
    });
    
    //     启动定时器
    dispatch_resume(self.searchTimer);
}
#pragma mark - private
- (void)goProtocolDetailWithKind:(int)kind
{
    UIViewController *vc = [[UIViewController alloc] initWithClassName:@"LProtocolShowViewController"];
    vc.paraObject = [NSNumber numberWithInt:kind];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -event response

- (void)tapClick
{
    [self.view endEditing:YES];
}


#pragma mark -getters and setters
-(UITableView *)tableView{
    if (!_tableView){
        _tableView =[[UITableView alloc] initWithFrame:CGRectMake(0, lTopBarHeight + 106, lScreenWidth, lScreenHeight - lTopBarHeight - 106) style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.bounces = NO;
        [_tableView setBackgroundColor:lClearColor];
        [_tableView setSeparatorColor:rgba(229, 229, 229, 1)];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    
    return _tableView;
}

-(UIView *)searchView
{
    if (!_searchView)
    {
        
        _searchView =[[UIView alloc] initWithFrame:CGRectMake(0, lTopBarHeight, lScreenWidth,106)];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
            [_searchView addGestureRecognizer:tap];
        _searchView.backgroundColor = lWhiteColor;
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(10, self.searchTextFiled.bottom + 11, 13, 16)];
        icon.image = IMAGENAMED(@"ic_location");
       
        UILabel *addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(33, self.searchTextFiled.bottom, lScreenWidth - 33 - 74, 56)];
        addressLabel.font = MFontWithSize(16);
        addressLabel.text = self.city;
        [addressLabel setTextAlignment:NSTextAlignmentLeft];
        addressLabel.textColor = rgba(51, 51, 51, 1);
        self.addressLab = addressLabel;
        UIButton *modiftyBtn = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(addressLabel.right + 10, self.searchTextFiled.bottom, 54, 26);
            [button setTitle:@"修改" forState:UIControlStateNormal];
            button.titleLabel.font = MFontWithSize(12);
            [button setTitleColor:lWhiteColor forState:UIControlStateNormal];
            button.backgroundColor = rgba(12, 183, 108, 1);
            [button setAllCorner:14];
            [button addTarget:self action:@selector(modiftyBtnAction) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
        modiftyBtn.centerY = addressLabel.centerY;
        icon.centerY = addressLabel.centerY;
        [_searchView addSubview:self.searchTextFiled];
        [_searchView addSubview:icon];
        [_searchView addSubview:addressLabel];
        [_searchView addSubview:modiftyBtn];
       
    }
    
    return _searchView;
}

-(UITextField *)searchTextFiled
{
    if (!_searchTextFiled)
    {
        _searchTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(10, 10, lScreenWidth - 20, 40)];
        _searchTextFiled.font = MFontWithSize(16);
        _searchTextFiled.textColor = rgba(51, 51, 51, 1);
        _searchTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _searchTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"没有找到你的学校？试试搜索" attributes:@{NSFontAttributeName:RFontWithSize(14)}];
        _searchTextFiled.delegate =self;
       // [_searchTextFiled setInputAccessoryView:self.customTextFieldInputAccessoryView];
        if (@available(iOS 11.0,*)) {
            _searchTextFiled.textContentType =UITextContentTypeUsername;
        }
        [_searchTextFiled setAllCornersWithCornerRadius:20];
        _searchTextFiled.backgroundColor = rgba(245, 245, 245, 1);
      //  [_searchTextFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        [_searchTextFiled addTarget:self action:@selector(textEnd:) forControlEvents:UIControlEventEditingDidEnd];
        UIView *leftSpaceView = [[UIView alloc] init];
        leftSpaceView.frame = CGRectMake(0,0,15,40);
        leftSpaceView.backgroundColor =rgba(245, 245, 245, 1);
        _searchTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _searchTextFiled.leftView = leftSpaceView;
        
        UIView *rightSpaceView = [[UIView alloc] init];
        rightSpaceView.frame = CGRectMake(0,0,60,40);
        rightSpaceView.backgroundColor =rgba(245, 245, 245, 1);
        UIButton *btn = [UIButton new];
        btn.frame =CGRectMake(0, 0, 60, 40);
        
        [btn setImage:IMAGENAMED(@"ic_search") forState:UIControlStateNormal];
        [rightSpaceView addSubview:btn];
        _searchTextFiled.rightViewMode = UITextFieldViewModeAlways;
        _searchTextFiled.rightView = rightSpaceView;
    }

    return _searchTextFiled;
}
- (AddressPickView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[AddressPickView alloc] initWithFrame:lApp.window.bounds];
        
        WeakSelf(self);
        _pickerView.block = ^(NSString * _Nonnull address) {
            weakself.addressLab.text = address;
            weakself.city = address;
            [weakself loadData];
        };
    }
    return _pickerView;
}

@end
